package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"mock/grpc_test/proto"
	"net"
)

type Server struct {}

func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply, error) {

	//业务逻辑
	return &proto.HelloReply{
		Message: "hello " + request.Name,
	}, nil
}

func main() {
	interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		fmt.Println("接收到了请求")
		//在函数执行前处理业务
		//return handler(ctx, req)  //直接返回，后面直接处理请求
		i, err := handler(ctx, req)
		//在函数执行后处理业务
		fmt.Println("在函数执行后处理")
		return i,err
	}
	opt := grpc.UnaryInterceptor(interceptor)
	server := grpc.NewServer(opt)
	proto.RegisterGreeterServer(server, &Server{})
	listen, err := net.Listen("tcp", "0.0.0.0:8888")
	if err != nil {
		panic("failed to listen :" + err.Error())
	}
	err = server.Serve(listen)
	if err != nil {
		panic("failed to start grpc:" + err.Error())
	}
}